package com.gsit.ocrbatch.controller;

import static com.gsit.ocrbatch.utils.FileConstant.FILE_PATH_SEPARATOR;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.gsit.ocrbatch.domain.Record;
import com.gsit.ocrbatch.domain.WebConfig;
import com.gsit.ocrbatch.services.OcrFileReader;
import com.gsit.ocrbatch.services.OcrFileWriter;
import com.gsit.ocrbatch.services.RecordService;
import com.gsit.ocrbatch.utils.FileConstant.FileFlow;


@Repository
public class OcrProcesser {
	
	private List<Record> records = new ArrayList<Record>();
	
	@PersistenceContext
	private EntityManager entityManager;
	
	@Autowired
	private RecordService recordService;
	
	@Autowired
	private OcrFileReader fileReader;
	
	@Autowired
	private OcrFileWriter fileWriter;
	
	@Autowired
	private WebConfig webConfig; 
	
	@Transactional
	public void execute(final FileFlow fileFlow, Record record)throws Exception{
		read(fileFlow, record);
		process(records);
		write(fileFlow);
	}
	
	
	private void read(final FileFlow fileFlow,Record record)throws Exception{
		records.clear();
		if(FileFlow.PROCESS == fileFlow){
			
			if(webConfig.getExternalFileLoaderEnable()){
				//fileWriter.writeFolderToFolder(new File(new URI(webConfig.getExternalInFileLoaction())),webConfig.getApacheFilePath()+FILE_PATH_SEPARATOR+fileFlow.getInFolder().getPath()+FILE_PATH_SEPARATOR);
				fileWriter.writeFolderToFolder(new File(webConfig.getExternalInFileLoaction()),webConfig.getApacheFilePath()+FILE_PATH_SEPARATOR+fileFlow.getInFolder().getPath()+FILE_PATH_SEPARATOR);
			}
			
			
			records.addAll(fileReader.read(fileFlow));
		}else{
			records.add(record);
		}
		
	}
	
	
	private void write(final FileFlow fileFlow)throws IOException{
		fileWriter.write(records,fileFlow);
	}
	
	
	private void process(List<Record> records) throws Exception {
		for (Record record : records) {
			recordService.save(record);
		}
		entityManager.clear();
	}
	
	public void show(){
		for (Record record : records) {
			System.out.println(" >>>>>>>>"+record.getName());
		}
	}
	
	
	

}
